

class WSModule {

  constructor(url, eventHanlder = ()=>{}) {
    this.isClose = false //不再次自动连接websocket, false=自动连接, true=不自动连接
    this.connect(url, eventHanlder)
  }
  connect(url,eventHanlder){
    this.connectOK = false
    this.ws = uni.connectSocket({
      url,
      success: ()=> {
        this.connectOK = true
      },
      fail: ()=> {
        console.log('WebSocket连接打开失败！');
      },
      complete: ()=> {}
    });

    this.ws.onOpen(()=>{
      console.log('WebSocket连接已打开！');
    })
    this.ws.onClose(()=>{
      console.log('WebSocket 已关闭！');
      //重新连接
      if(!this.isClose){
        this.connect(url,eventHanlder)
      }
    })
    this.ws.onError(()=>{
      console.log('监听 WebSocket 错误！');
    })

    this.ws.onMessage((msg)=>{
      console.log('接受到消息:', msg);
      eventHanlder(msg)
    })
  }
  send(msg,success=()=>{},fail=null){
    let fail2 = fail
    if(fail2===null){
      fail2 = ()=>{uni.showToast({ title: "消息发送失败,请稍后再试!", duration: 2000, icon: "none" })}
    }
    let options = {
      data: msg,
      success: success(),
    }
    this.ws.send(options)
  }
  close(){
    console.log("主动关闭,不自动再次连接")
    this.isClose = true //不再次自动连接websocket, false=自动连接, true=不自动连接
  }
}
export default WSModule;